package com.cloud.service;/**
 * @author cRyann
 * @create 2017-03-27 15:37
 **/

import com.cloud.model.system.SysResource;
import com.cloud.model.system.SysRole;
import com.cloud.model.system.SysUser;
import com.cloud.repository.SysUserRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author cRyann
 * @create 2017-03-27 15:37
 **/
@Service
public class SysUserService {
    @Autowired
    private SysUserRepository sysUserRepository;

    public SysUser findUserByUserName(String username) {
        return sysUserRepository.findByUserName(username);
    }

    public Set<SysRole> getRolesBySysUserName(String username) {
        return sysUserRepository.findByUserName(username).getRoles();
    }

    public Set<SysResource> getResourceBySysUserName(String username) {
        Set<SysRole> roles = sysUserRepository.findByUserName(username).getRoles();
        Set<SysResource> sysresources = new HashSet<SysResource>();
        for (SysRole role : roles) {
            Set<SysResource> resources = role.getSysresources();
            for (SysResource resource : resources)
                sysresources.add(resource);
        }
        return sysresources;
    }
    /**
     * 按条件分页查询
     * @param user
     * @param page
     * @param size
     * @return
     */
    public Page<SysUser> findAll(SysUser user,int page,int size) {
        Pageable pageable=new PageRequest(page,size,new Sort("id"));
        Specification<SysUser> specification=new Specification<SysUser>() {
            @Override
            public Predicate toPredicate(Root<SysUser> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                if (StringUtils.isNotBlank(user.getUserName())){
                    Path<String> userName=root.get("userName");
                    query.where(cb.like(userName,user.getUserName()+"%"));
                }
                return null;
            }
        };
        return sysUserRepository.findAll(specification,pageable);
    }
    /**
     * 删除
     *
     * @param list
     * @return
     */
    @Transactional
    public void delete(List<SysUser> list) {
        sysUserRepository.deleteInBatch(list);
    }

    /**
     * 根据id查找
     *
     * @param id
     * @return
     */
    public SysUser findOne(Long id) {
        return sysUserRepository.findOne(id);
    }


    @Transactional
    public SysUser saveUser(SysUser sysUser) {
       return sysUserRepository.save(sysUser);
    }
}
